<template>
  <div class="dt-cropper" :style="getStyle">
    <div class="image-wrapper" :style="getImageWrapperStyle" @click="chooseImg">
      <div class="image-mask" v-if="!sourceValue">
        <i class="i mdi:cloud-upload-outline" :style="maskIconStyle"></i>
      </div>
      <img :src="sourceValue" v-if="sourceValue" />
    </div>

    <AButton class="upload-btn" @click="chooseImg">选择图片</AButton>

    <CopperModal @register="register"></CopperModal>
  </div>
</template>

<script lang="ts" setup>
import { useModalOut } from '@zm-pkg/ui'
import { useMessage } from '@zm-pkg/core'
import { CSSProperties } from 'vue'
import { default as CopperModal } from './CopperModal.vue'
import { basicProps } from './props'

import 'cropperjs/dist/cropper.css'

const { message } = useMessage()
const [register, { openModal, closeModal }] = useModalOut()

const props = defineProps( basicProps )
const emits = defineEmits(['update:value', 'change'])
const sourceValue = ref(props.src || '')

const getStyle = computed((): CSSProperties => {
  return {
    width: `${props.width}`.replace(/px/, '') + 'px',
  }
})

const getImageWrapperStyle = computed((): CSSProperties => {
  let style: CSSProperties = {
    width: `${props.width}`.replace(/px/, '') + 'px',
    height: `${props.height}`.replace(/px/, '') + 'px'
  }

  if( props.circled ) {
    style = {
      ...style,
      borderRadius: '50%',
      overflow: 'hidden'
    }
  }

  return style
})

const maskIconStyle = computed(() => {
  return {
    fontSize: parseInt(`${props.width}`.replace(/px/, '')) / 2 + 'px'
  }
})

function chooseImg() {
  openModal(
      props,
      ({ source, data }) => {
        sourceValue.value = source

        emits('change', { source, data })
        message.success('图片裁剪成功！')
      }
  )
}

watchEffect(() => {
  sourceValue.value = props.src || ''
})

watch(
    () => sourceValue.value,
    (v: string) => {
      emits('update:value', v)
    }
)

defineExpose({ openModal: openModal.bind(null, true), closeModal })

</script>

<style lang="less" scoped>
.dt-cropper{
  display: block;
  background-color: #fff;

  text-align: center;

  .image-wrapper{
    width: 100%;
    height: 100%;
    border: 1px solid #d9d9d9;
    position: relative;
    img{
      cursor: pointer;
    }
  }
  .image-mask{
    position: absolute;
    background: rgba(0,0,0,.4);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    opacity: 0.6;
    transition: opacity .4s;
    i{
      color: rgb(214, 214, 214);
    }
    &:hover{
      opacity: 1;
    }
  }

  .upload-btn{
    margin: 20px auto 0;
  }
}
</style>